<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="9">
          <div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              clearable
              @clear="getUsersList"
              @input="getUsersList"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUsersList"
              >
              </el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-button
              type="primary"
              @click="isDialogVisible=true"
            >添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <el-table
        :data="userList"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="编号"
          width="50px"
        >
        </el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
          width="100px"
        >
        </el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
        >
        </el-table-column>
        <el-table-column
          label="电话"
          prop="mobile"
        >
        </el-table-column>
        <el-table-column
          label="角色"
          prop="role_name"
          width="100px"
        >
        </el-table-column>
        <el-table-column
          label="状态"
          prop="mg_state"
          width="100px"
        >
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button-group>
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="editiUserInfo(scope.row.id)"
              ></el-button>
              <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  @click="setUserRole(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="isDialogVisible"
      width="50%"
      center
      @close="addUsersClose"
    >
      <!-- 对话框内容主体区域 -->
      <span>
        <el-form
          :model="ruleForm"
          status-icon
          :rules="addUsersRules"
          ref="addUsersRef"
          label-width="100px"
        >
          <el-form-item
            label="用户名称"
            prop="username"
          >
            <el-input
              type="text"
              v-model="ruleForm.username"
              autocomplete="off"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
            required
          >
            <el-input
              type="password"
              v-model="ruleForm.password"
              autocomplete="off"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input
              v-model.number="ruleForm.email"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="mobile"
          >
            <el-input
              v-model.number="ruleForm.mobile"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 对话框 底部按钮 区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="isDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUsers"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息的 Dialog -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="isEditiDialogVisible"
      width="50%"
      center
      @close="editUsersClose"
    >
      <span>
        <el-form
          label-width="80px"
          :model="editiForm"
          :rules="editiUsersRules"
          ref="editiFormRef"
        >
          <el-form-item label="用户名">
            <el-input
              v-model="editiForm.username"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input v-model="editiForm.email"></el-input>
          </el-form-item>
          <el-form-item
            label="手机"
            prop="mobile"
          >
            <el-input v-model="editiForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="isEditiDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="postEditiUsers"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户角色的 Dialog -->
    <el-dialog
      title="修改用户角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      center
      @close="closeSetRolesDialog"
    >
      <el-form :model="userInfo">
        <el-form-item label="用户名称:">
          {{ userInfo.username }}
        </el-form-item>
        <el-form-item label="当前用户角色:">
          {{ userInfo.role_name }}
        </el-form-item>
        <el-form-item label="修改用户角色:">
          <el-select
            v-model="selectedRoleId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in rolesInfo"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="postSetRolesForm"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    var validateUserName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    var validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入邮箱'))
      } else {
        callback()
      }
    }
    var validateMobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else {
        callback()
      }
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editiForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      userInfo: {},
      rolesInfo: [],
      addUsersRules: {
        username: [
          { required: true, validator: validateUserName, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ]
      },
      editiUsersRules: {
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ]
      },
      userList: [],
      total: 0,
      selectedRoleId: '',
      isDialogVisible: false,
      isEditiDialogVisible: false,
      setRoleDialogVisible: false
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    async getUsersList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pageSize 的改变
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    // 监听 当前页码 的改变
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUsersList()
    },
    async userStateChange (rowData) {
      const { data: res } = await this.$http.put(`users/${rowData.id}/state/${rowData.mg_state}`)
      if (res.meta.status !== 200) {
        return this.$message.error('修改用户状态失败!')
      } else {
        this.$message.success('修改用户状态成功!')
      }
    },
    addUsersClose () {
      this.$refs.addUsersRef.resetFields()
    },
    addUsers () {
      // 在提交 添加用户请求时 进行表单预校验
      this.$refs.addUsersRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请输入完整信息!')
        }
        // 发起添加用户的请求
        const { data: res } = await this.$http.post('users', this.ruleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败!')
        }
        this.$message.success('添加用户成功!')
        this.isDialogVisible = false
        this.getUsersList()
      })
    },
    async editiUserInfo (id) {
      // 点击发生后，先展示对话框
      this.isEditiDialogVisible = true
      // 发起请求
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('获取用户信息失败!')
      } else {
        this.editiForm.id = res.data.id
        this.editiForm.username = res.data.username
        this.editiForm.email = res.data.email
        this.editiForm.mobile = res.data.mobile
      }
    },
    // 点击 确定 提交用户修改信息
    postEditiUsers () {
      // 预校验
      this.$refs.editiFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('请输入完整信息')
        } else {
          const { data: res } = await this.$http.put('users/' + this.editiForm.id, { id: this.editiForm.id, email: this.editiForm.email, mobile: this.editiForm.mobile })
          if (res.meta.status !== 200) {
            this.$message.error('更新用户信息失败!')
          }
          this.$message.success('修改信息成功!')
          this.isEditiDialogVisible = false
          this.getUsersList()
        }
      })
    },
    // 关闭 编辑用户信息时 清空editiForm
    editUsersClose () {
      this.$refs.editiFormRef.resetFields()
    },
    async removeUserById (id) {
      const confirmInfo = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      if (confirmInfo === 'confirm') {
        this.$http.delete('users/' + id)
        this.getUsersList()
        this.$message.success('删除用户成功!')
      }
    },
    async setUserRole (userInfo) {
      this.userInfo = userInfo
      // 请求用户角色列表，并保存到 rolesInfo 中
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败!')
      }
      this.rolesInfo = res.data
      this.setRoleDialogVisible = true
    },
    closeSetRolesDialog () {
      this.selectedRoleId = ''
    },
    // 提交用户修改的角色
    async postSetRolesForm () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择一个用户角色!')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role/`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('修改用户角色失败!')
      }
      this.$message.success('修改用户角色成功!')
      this.getUsersList()
      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  padding: 15px;
}
.el-row {
  padding: 15px;
}
.el-pagination {
  padding: 15px;
  text-align: center;
}
</style>
